#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int money = 0;      //提款数
int bank_balance = 10000;    //存款余额

pthread_mutex_t mutex;    //定义互斥锁

void* pthread_fun0(void *arg)
{
    printf("主卡提款中...\n");
    sleep(1);

    //【3】对共享资源的操作进行加锁
    pthread_mutex_lock(&mutex);

    printf("主卡余额 %d\n",bank_balance);
    printf("请输入主卡提款数:");
    scanf("%d",&money);
    sleep(1);
    if(money <= bank_balance)
    {
        bank_balance -= money;
        printf("提款成功%d,主卡余额 %d\n",money,bank_balance);
    }
    else
    {
        printf("提款失败,余额不足\n");
    }

    //【4】对共享资源的操作完成，进行解锁
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

void* pthread_fun1(void *arg)
{
    printf("副卡提款中...\n");
    sleep(1);

    //【3】对共享资源的操作进行加锁
    pthread_mutex_lock(&mutex);

    printf("副卡余额 %d\n",bank_balance);
    printf("请输入副卡提款数:");
    
    scanf("%d",&money);
    sleep(1);
    if(money <= bank_balance)
    {
        bank_balance -= money;
        printf("提款成功%d,副卡余额 %d\n",money,bank_balance);
    }
    else
    {
        printf("提款失败,余额不足\n");
    }

    //【4】对共享资源的操作完成，进行解锁
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

int main()
{
    //【2】初始化互斥锁
    pthread_mutex_init(&mutex,NULL);

    printf("进程执行中...\n");
    pthread_t id[2];
    if(pthread_create(&id[0],NULL,pthread_fun0,NULL) == -1)
    {
        perror("fail to pthread");
        exit(-1);
    }
    if(pthread_create(&id[1],NULL,pthread_fun1,NULL) == -1)
    {
        perror("fail to pthread");
        exit(-1);
    }
    pthread_join(id[0],NULL);
    pthread_join(id[1],NULL);

    //销毁互斥锁
    pthread_mutex_destroy(&mutex);
    printf("进程退出\n");
    return 0;
}